package com.studentmanagement.ui;

import com.studentmanagement.model.Student;
import com.studentmanagement.model.User;
import com.studentmanagement.service.StudentService;
import com.studentmanagement.service.UserService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class StudentEditDialog extends JDialog {
    private JTextField studentIdField;
    private JTextField nameField;
    private JComboBox<String> genderComboBox;
    private Map<String, String> genderMap = new HashMap<>();
    private JTextField departmentField;
    private JTextField majorField;
    private JTextField contactField;
    private JTextField emailField;
    private JTextField addressField;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton saveButton;
    private JButton cancelButton;
    private boolean saved = false;
    private StudentService studentService = new StudentService();
    private UserService userService = new UserService();
    private Student student;

    public StudentEditDialog(Student student) {
        this.student = student;
        setTitle(student == null ? "新增学生" : "编辑学生");
        setModal(true);
        initComponents();
        setupLayout();
        setupListeners();
        if (student != null) {
            fillForm(student);
        }
        pack();
        setLocationRelativeTo(null);
    }

    private void initComponents() {
        studentIdField = new JTextField(15);
        nameField = new JTextField(15);
        
        genderMap.put("男", "MALE");
        genderMap.put("女", "FEMALE");
        genderMap.put("其他", "OTHER");
        
        String[] genderOptions = {"男", "女", "其他"};
        genderComboBox = new JComboBox<>(genderOptions);
        genderComboBox.setSelectedItem("其他");
        
        departmentField = new JTextField(15);
        majorField = new JTextField(15);
        contactField = new JTextField(15);
        emailField = new JTextField(15);
        addressField = new JTextField(20);
        usernameField = new JTextField(15);
        passwordField = new JPasswordField(15);
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");
    }

    private void setupLayout() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(6, 6, 6, 6);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        int row = 0;
        if (student == null) {
            gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("用户名:"), gbc);
            gbc.gridx = 1; formPanel.add(usernameField, gbc); row++;
            gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("密码:"), gbc);
            gbc.gridx = 1; formPanel.add(passwordField, gbc); row++;
        }
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("学号:"), gbc);
        gbc.gridx = 1; formPanel.add(studentIdField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("姓名:"), gbc);
        gbc.gridx = 1; formPanel.add(nameField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("性别:"), gbc);
        gbc.gridx = 1; formPanel.add(genderComboBox, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("院系:"), gbc);
        gbc.gridx = 1; formPanel.add(departmentField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("专业:"), gbc);
        gbc.gridx = 1; formPanel.add(majorField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("联系电话:"), gbc);
        gbc.gridx = 1; formPanel.add(contactField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("邮箱:"), gbc);
        gbc.gridx = 1; formPanel.add(emailField, gbc); row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("地址:"), gbc);
        gbc.gridx = 1; formPanel.add(addressField, gbc); row++;

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        setLayout(new BorderLayout(10, 10));
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupListeners() {
        saveButton.addActionListener(this::onSave);
        cancelButton.addActionListener(e -> dispose());
    }

    private void fillForm(Student s) {
        studentIdField.setText(s.getStudentId());
        nameField.setText(s.getName());
        
        String gender = s.getGender();
        if ("MALE".equals(gender)) {
            genderComboBox.setSelectedItem("男");
        } else if ("FEMALE".equals(gender)) {
            genderComboBox.setSelectedItem("女");
        } else {
            genderComboBox.setSelectedItem("其他");
        }
        
        departmentField.setText(s.getDepartment());
        majorField.setText(s.getMajor());
        contactField.setText(s.getContactNumber());
        emailField.setText(s.getEmail());
        addressField.setText(s.getAddress());
        usernameField.setEnabled(false);
        passwordField.setEnabled(false);
    }

    private void onSave(ActionEvent e) {
        if (studentIdField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "学号和姓名不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (student == null) {
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());
            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (userService.getUserByUsername(username) != null) {
                JOptionPane.showMessageDialog(this, "用户名已存在，请更换！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRole(User.UserRole.STUDENT);
            boolean userCreated = userService.insertUser(user);
            if (!userCreated) {
                JOptionPane.showMessageDialog(this, "用户创建失败！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            User createdUser = userService.getUserByUsername(username);
            if (createdUser == null) {
                JOptionPane.showMessageDialog(this, "用户创建后获取信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            student = new Student();
            student.setUserId(createdUser.getId());
        }
        student.setStudentId(studentIdField.getText().trim());
        student.setName(nameField.getText().trim());
        String selectedGender = (String) genderComboBox.getSelectedItem();
        student.setGender(genderMap.get(selectedGender));
        student.setDepartment(departmentField.getText().trim());
        student.setMajor(majorField.getText().trim());
        student.setContactNumber(contactField.getText().trim());
        student.setEmail(emailField.getText().trim());
        student.setAddress(addressField.getText().trim());
        student.setBirthDate(new Date());
        boolean success;
        if (student.getId() == null) {
            success = studentService.insertStudent(student);
        } else {
            success = studentService.updateStudent(student);
        }
        if (success) {
            saved = true;
            JOptionPane.showMessageDialog(this, "保存成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "保存失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public boolean isSaved() {
        return saved;
    }
} 